package com.ch.common.net.retrofit

import com.ch.common.utils.LogUtils
import okhttp3.Call
import okhttp3.HttpUrl
import okhttp3.Request

abstract class ReplaceUrlCallFactory(delegate: Call.Factory) : CallFactoryProxy(delegate) {
    override fun newCall(request: Request): Call {
        /*
         *TODO 动态添加baserUrl以下二种方式
         * @Headers("BaseUrlName:xxx") for method, or
         * method(@Header("BaseUrlName") String name) for parameter
         */
        val baseUrlName = request.header(BASE_URL_NAME)
        if (baseUrlName != null) {
            val newHttpUrl = getNewUrl(baseUrlName, request)
            if (newHttpUrl != null) {
                val newRequest = request.newBuilder().url(newHttpUrl).build()
                return delegate.newCall(newRequest)
            } else {
                LogUtils.w("getNewUrl() return null when baseUrlName==$baseUrlName");
            }
        }
        return delegate.newCall(request)
    }

    /**
     * @param baseUrlName name to sign baseUrl
     * @return new httpUrl, if null use old httpUrl
     */
    protected abstract fun getNewUrl(baseUrlName: String?, request: Request?): HttpUrl?

    companion object {
        private const val BASE_URL_NAME = "BaseUrlName"
    }
}